package com.ccx.coachsite.ui.softmgr;


import java.util.ArrayList;
import java.util.HashMap;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.ccx.coachsite.R;
import com.ccx.coachsite.api.CoachSiteSoftMgrApiAccessor;
import com.ccx.coachsite.downloadmgr.AsyncImageLoaderDetail;
import com.ccx.coachsite.downloadmgr.AsyncImageLoaderDetail.ImageCallback;
import com.ccx.coachsite.model.PageInfo;
import com.ccx.coachsite.model.ServerResult;
import com.ccx.coachsite.model.SoftKeywordItem;
import com.ccx.coachsite.ui.CommonAppView;
import com.ccx.coachsite.util.OpenShareQQWeiBo;

/**
 * 搜索模块
 * @author Cfb
 *
 */

public class SoftMgrSearchView  extends CommonAppView implements SoftMgrSoftListView.Callback {

	private static ServerResult<SoftInfo> listSoftInfo;
	private static ServerResult<SoftKeywordItem> listHotKey;
	
	//点击Item后把分类结果展示在此View
	private SoftMgrSoftListView searchResultView = null; 	
	
	//快捷搜索  热门
	private TextView search_hot;
	
	LinearLayout wait_layout;
	
	//搜索结果是否设置的标志
	private boolean bSetResultHit = false;
	
	public boolean searchNameType = false;//false 通过关键词查询   True通过名称查询
	
	LinearLayout resultLayout;

	View searchKey_ll;//热门词布局
	View hot_soft_ll;//热门软件布局
	
	private static final String TAG = "SoftMgrSearchView";
	
	Context ctx;
	
	private FrameLayout container;
	
	/**
	 * 搜索框
	 */
	public EditText mEditKeyword;
	
	/**
	 * 搜索关键词
	 */
	private String mKeyword;
	
	/**
	 * 搜索按钮
	 */
	private Button mButtonSearch;
	
	/**
	 * 搜索结果标签
	 */
	private TextView mTextViewResult;
	
	/**
	 * 热门搜索词更新消息
	 */
	private static final int HOTKEY_UPDATE = 1;	
	
	/**
	 * 热门达人推荐应用新消息
	 */
	private static final int HOTSOFT_UPDATE = 2;	
	
	private TextView mTextView1, mTextView2, mTextView3, mTextView4,
		mTextView5, mTextView6, mTextView7, mTextView8, mTextView9,
		mTextView10;
	private Animation animation1, animation2, animation3, animation4,animation5,
		animation6, animation7, animation8, animation9, animation10,
		animation2_1, animation2_2, animation2_3, animation2_4, animation2_5, 
		animation2_6, animation2_7, animation2_8, animation2_9, animation2_10;
	
	private LinearLayout hot_soft_Layout_1,hot_soft_Layout_2,hot_soft_Layout_3,hot_soft_Layout_4;
	private ImageView hot_soft_btn_1,hot_soft_btn_2,hot_soft_btn_3,hot_soft_btn_4;
	private TextView hot_soft_btn_1_text,hot_soft_btn_2_text,hot_soft_btn_3_text,hot_soft_btn_4_text;
	
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case HOTKEY_UPDATE:
				wait_layout.setVisibility(View.GONE);				
				
				if (listSoftInfo!=null && listHotKey!=null)
					initQuickSearch(listSoftInfo.itemList, listHotKey.itemList);
				
				break;			
			}
		}
	};
	
	public SoftMgrSearchView(Context paramContext) {
		super(paramContext);
		
		ctx = paramContext;
		
		addView(R.layout.soft_mgr_soft_search);		
		
		wait_layout = (LinearLayout) findViewById(R.id.wait_layout);
	}
		
	public void loadHotSoftAndHotKey(){
		
		// 加载分类及热门软件
		new Thread(new Runnable() {
			@Override
			public void run() {
				if ( listSoftInfo==null ) {
					listSoftInfo = CoachSiteSoftMgrApiAccessor.getSoftMgRecommendList();
				}
				if ( listHotKey==null ) {
					listHotKey = CoachSiteSoftMgrApiAccessor.getSoftMgrKeywordList();
				}
				Message msg = handler.obtainMessage(HOTKEY_UPDATE);
				msg.sendToTarget();
			}
		}).start();
	}
	
	private void initQuickSearch(ArrayList<SoftInfo> listHotSoft, ArrayList<SoftKeywordItem> listHotKey) {
		
		AsyncImageLoaderDetail mAsyncImageLoader = new AsyncImageLoaderDetail();
		
		for (int i = 0; i < listHotSoft.size(); i++) {
			
			final SoftInfo softInfo = listHotSoft.get( i );
			if (i==1){ 
				hot_soft_Layout_1.setVisibility(View.VISIBLE);
				hot_soft_btn_1.setTag(softInfo);
				hot_soft_btn_1.setOnClickListener(hotSoftListener);
				
				Drawable cachedImage = mAsyncImageLoader.loadDrawable(softInfo.getIconUrl(), new ImageCallback() {
		            public void imageLoaded(Drawable imageDrawable, String imageUrl) {
		            	
		                if (hot_soft_btn_1 != null && imageDrawable!=null) {
		                	hot_soft_btn_1_text.setText(softInfo.getTitle());
		                	hot_soft_btn_1.setImageDrawable(imageDrawable);
		                    AlphaAnimation aa = new AlphaAnimation(0.7f, 1.0f);
		                    aa.setDuration(300);
		                    hot_soft_btn_1.startAnimation(aa);	
		                }	                
		            }
		        });
				
			}
			if (i==2){ 
				hot_soft_Layout_2.setVisibility(View.VISIBLE);
				hot_soft_btn_2.setTag(softInfo);
				hot_soft_btn_2.setOnClickListener(hotSoftListener);
				
				Drawable cachedImage = mAsyncImageLoader.loadDrawable(softInfo.getIconUrl(), new ImageCallback() {
		            public void imageLoaded(Drawable imageDrawable, String imageUrl) {
		            	
		                if (hot_soft_btn_2 != null && imageDrawable!=null) {
		                	hot_soft_btn_2_text.setText(softInfo.getTitle());
		                	hot_soft_btn_2.setImageDrawable(imageDrawable);
		                    AlphaAnimation aa = new AlphaAnimation(0.7f, 1.0f);
		                    aa.setDuration(300);
		                    hot_soft_btn_2.startAnimation(aa);	
		                }	                
		            }
		        });
			}
			if (i==3){ 
				hot_soft_Layout_3.setVisibility(View.VISIBLE);
				hot_soft_btn_3.setTag(softInfo);
				hot_soft_btn_3.setOnClickListener(hotSoftListener);
				
				Drawable cachedImage = mAsyncImageLoader.loadDrawable(softInfo.getIconUrl(), new ImageCallback() {
		            public void imageLoaded(Drawable imageDrawable, String imageUrl) {
		            	
		                if (hot_soft_btn_3 != null && imageDrawable!=null) {
		                	hot_soft_btn_3_text.setText(softInfo.getTitle());
		                	hot_soft_btn_3.setImageDrawable(imageDrawable);
		                    AlphaAnimation aa = new AlphaAnimation(0.7f, 1.0f);
		                    aa.setDuration(300);
		                    hot_soft_btn_3.startAnimation(aa);	
		                }	                
		            }
		        });
			}
			if (i==4){ 
				hot_soft_Layout_4.setVisibility(View.VISIBLE);
				hot_soft_btn_4.setTag(softInfo);
				hot_soft_btn_4.setOnClickListener(hotSoftListener);

				Drawable cachedImage = mAsyncImageLoader.loadDrawable(softInfo.getIconUrl(), new ImageCallback() {
		            public void imageLoaded(Drawable imageDrawable, String imageUrl) {
		            	
		                if (hot_soft_btn_4 != null && imageDrawable!=null) {
		                	hot_soft_btn_4_text.setText(softInfo.getTitle());
		                	hot_soft_btn_4.setImageDrawable(imageDrawable);
		                    AlphaAnimation aa = new AlphaAnimation(0.7f, 1.0f);
		                    aa.setDuration(300);
		                    hot_soft_btn_4.startAnimation(aa);	
		                }	                
		            }
		        });
			}
			if (i>3) break;//布局文件默认只显示12个分类 
			/*
			int categoryResID = getResources().getIdentifier("shop_theme_category_"+(i+1), "id", getContext().getPackageName());
			shop_theme_category = (TextView)findViewById( categoryResID );
			shop_theme_category.setText(catagory.name);
			shop_theme_category.setTag( catagory );
			shop_theme_category.setOnClickListener( catagorySearchListener );
			*/
		}
		
		//关键词最多10个
		
		for (int i = 0; i < listHotKey.size(); i++) {
			
			SoftKeywordItem hotKeyItem = listHotKey.get( i );
			
			if (i>9) break;
			
			int hotKeyResID = getResources().getIdentifier("txt"+(i+1), "id", getContext().getPackageName());
			search_hot = (TextView)findViewById( hotKeyResID );
			search_hot.setText( hotKeyItem.getKeyword() );
			search_hot.setOnClickListener( hotSearchListener );
		}
		
	}

	private void initAnimations() {
		animation1 = AnimationUtils.loadAnimation(ctx, R.anim.hotkey_anim1_1);
		animation2 = AnimationUtils.loadAnimation(ctx, R.anim.hotkey_anim1_2);
		animation3 = AnimationUtils.loadAnimation(ctx, R.anim.hotkey_anim1_3);
		animation4 = AnimationUtils.loadAnimation(ctx, R.anim.hotkey_anim1_4);
		animation5 = AnimationUtils.loadAnimation(ctx, R.anim.hotkey_anim1_5);
		animation6 = AnimationUtils.loadAnimation(ctx, R.anim.hotkey_anim1_6);
		animation7 = AnimationUtils.loadAnimation(ctx, R.anim.hotkey_anim1_7);
		animation8 = AnimationUtils.loadAnimation(ctx, R.anim.hotkey_anim1_8);
		animation9 = AnimationUtils.loadAnimation(ctx, R.anim.hotkey_anim1_9);
		animation10 = AnimationUtils.loadAnimation(ctx, R.anim.hotkey_anim1_10);
	}

	private void initAnimations2() {
		animation2_1 = AnimationUtils.loadAnimation(ctx, R.anim.hotkey_anim2_1);
		animation2_2 = AnimationUtils.loadAnimation(ctx, R.anim.hotkey_anim2_2);
		animation2_3 = AnimationUtils.loadAnimation(ctx, R.anim.hotkey_anim2_3);
		animation2_4 = AnimationUtils.loadAnimation(ctx, R.anim.hotkey_anim2_4);
		animation2_5 = AnimationUtils.loadAnimation(ctx, R.anim.hotkey_anim2_5);
		animation2_6 = AnimationUtils.loadAnimation(ctx, R.anim.hotkey_anim2_6);
		animation2_7 = AnimationUtils.loadAnimation(ctx, R.anim.hotkey_anim2_7);
		animation2_8 = AnimationUtils.loadAnimation(ctx, R.anim.hotkey_anim2_8);
		animation2_9 = AnimationUtils.loadAnimation(ctx, R.anim.hotkey_anim2_9);
		animation2_10 = AnimationUtils.loadAnimation(ctx, R.anim.hotkey_anim2_10);
	}
	
	private void startAnimations1() {
		mTextView1.startAnimation(animation1);
		mTextView2.startAnimation(animation2);
		mTextView3.startAnimation(animation3);
		mTextView4.startAnimation(animation4);
		mTextView5.startAnimation(animation5);
		mTextView6.startAnimation(animation6);
		mTextView7.startAnimation(animation7);
		mTextView8.startAnimation(animation8);
		mTextView9.startAnimation(animation9);
		mTextView10.startAnimation(animation10);
	}

	private void startAnimations2() {
		mTextView1.startAnimation(animation2_1);
		mTextView2.startAnimation(animation2_2);
		mTextView3.startAnimation(animation2_3);
		mTextView4.startAnimation(animation2_4);
		mTextView5.startAnimation(animation2_5);
		mTextView6.startAnimation(animation2_6);
		mTextView7.startAnimation(animation2_7);
		mTextView8.startAnimation(animation2_8);
		mTextView9.startAnimation(animation2_9);
		mTextView10.startAnimation(animation2_10);
	}
	
	private void randomTanslate() {

		startAnimations2();
	}
	
	public void initView() {
		
		container = (FrameLayout)this.findViewById( R.id.container );
		resultLayout = (LinearLayout) findViewById(R.id.result);
		mTextViewResult = (TextView)findViewById( R.id.resultTitle );
		
		searchKey_ll = findViewById(R.id.searchKey_ll);
		hot_soft_ll = findViewById(R.id.hot_soft_ll);
		
		mEditKeyword = (EditText)findViewById( R.id.keyword );
		
		mEditKeyword.setOnFocusChangeListener(new View.OnFocusChangeListener() {
			@Override
			public void onFocusChange(View v, boolean hasFocus) {
				
				if (hasFocus) {

					InputMethodManager imm = (InputMethodManager)ctx.getSystemService(Context.INPUT_METHOD_SERVICE);
					imm.showSoftInput(mEditKeyword, InputMethodManager.SHOW_IMPLICIT);
				} else {
					Log.d(TAG, "hasFocus false");
				}
			}
		});
		
		mButtonSearch = (Button)findViewById( R.id.clearImgBtn );
		mButtonSearch.setOnClickListener( new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				String sKeyword = mEditKeyword.getText().toString().trim(); 
				
				if( sKeyword.equals( "" ) ) {

					removeResultView();					
					Toast.makeText( ctx, R.string.common_search_condition, 2000 ).show();
					return;
				}
				
				searchNameType = true;
				
				searchByKeyWord(sKeyword);
			}
		});
		
		
		hot_soft_Layout_1 = (LinearLayout) hot_soft_ll.findViewById(R.id.hot_soft_layout_1);
		hot_soft_Layout_2 = (LinearLayout) hot_soft_ll.findViewById(R.id.hot_soft_layout_2);
		hot_soft_Layout_3 = (LinearLayout) hot_soft_ll.findViewById(R.id.hot_soft_layout_3);
		hot_soft_Layout_4 = (LinearLayout) hot_soft_ll.findViewById(R.id.hot_soft_layout_4);
		
		
		hot_soft_btn_1 = (ImageView) hot_soft_ll.findViewById(R.id.hot_soft_btn_1);
		hot_soft_btn_1_text = (TextView) hot_soft_ll.findViewById(R.id.hot_soft_btn_1_text);
		hot_soft_btn_1.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				
			}
		});
		
		
		hot_soft_btn_2 = (ImageView) hot_soft_ll.findViewById(R.id.hot_soft_btn_2);
		hot_soft_btn_2_text = (TextView) hot_soft_ll.findViewById(R.id.hot_soft_btn_2_text);
		
		hot_soft_btn_3 = (ImageView) hot_soft_ll.findViewById(R.id.hot_soft_btn_3);
		hot_soft_btn_3_text = (TextView) hot_soft_ll.findViewById(R.id.hot_soft_btn_3_text);
		
		hot_soft_btn_4 = (ImageView) hot_soft_ll.findViewById(R.id.hot_soft_btn_4);
		hot_soft_btn_4_text = (TextView) hot_soft_ll.findViewById(R.id.hot_soft_btn_4_text);
		
		mTextView1 = (TextView) searchKey_ll.findViewById(R.id.txt1);
		mTextView2 = (TextView) searchKey_ll.findViewById(R.id.txt2);
		mTextView3 = (TextView) searchKey_ll.findViewById(R.id.txt3);
		mTextView4 = (TextView) searchKey_ll.findViewById(R.id.txt4);
		mTextView5 = (TextView) searchKey_ll.findViewById(R.id.txt5);
		mTextView6 = (TextView) searchKey_ll.findViewById(R.id.txt6);
		mTextView7 = (TextView) searchKey_ll.findViewById(R.id.txt7);
		mTextView8 = (TextView) searchKey_ll.findViewById(R.id.txt8);
		mTextView9 = (TextView) searchKey_ll.findViewById(R.id.txt9);
		mTextView10 = (TextView) searchKey_ll.findViewById(R.id.txt10);
		
		mTextView1.setText( mTextView1.getText() );
		mTextView1.setOnClickListener( hotSearchListener );
		
		mTextView2.setText( mTextView2.getText() );
		mTextView2.setOnClickListener( hotSearchListener );
		
		mTextView3.setText( mTextView3.getText() );
		mTextView3.setOnClickListener( hotSearchListener );
		
		mTextView4.setText( mTextView4.getText() );
		mTextView4.setOnClickListener( hotSearchListener );
		
		mTextView5.setText( mTextView5.getText() );
		mTextView5.setOnClickListener( hotSearchListener );
		
		mTextView6.setText( mTextView6.getText() );
		mTextView6.setOnClickListener( hotSearchListener );
		
		mTextView7.setText( mTextView7.getText() );
		mTextView7.setOnClickListener( hotSearchListener );
		
		mTextView8.setText( mTextView8.getText() );
		mTextView8.setOnClickListener( hotSearchListener );
		
		mTextView9.setText( mTextView9.getText() );
		mTextView9.setOnClickListener( hotSearchListener );
		
		mTextView10.setText( mTextView10.getText() );
		mTextView10.setOnClickListener( hotSearchListener );
		
		//initAnimations();
		
		initAnimations2();
		
		loadHotSoftAndHotKey();
	}

	public void searchByKeyWord(String keyword ){
		
		removeResultView();
		
		mKeyword = keyword;		
		bSetResultHit = false;
		
		HashMap<String, Object> initParaMap = new HashMap<String, Object>();
		initParaMap.put( SoftMgrSoftListView.EXTRA_LIST_TYPE, SoftMgrSoftListView.TYPE_SEARCH_LIST );
		initParaMap.put( "keyWord", mKeyword );
		initParaMap.put( "searchNameType", searchNameType );
		
		searchResultView = new SoftMgrSoftListView(ctx, initParaMap);
		searchResultView.initData();
		searchResultView.setResultCallBack(this);		
		container.addView( searchResultView );
		
		hideKeyboard(ctx,mEditKeyword);
	}

	public static void hideKeyboard(Context ctx, View view){
		if( null == view ) return;
		InputMethodManager imm = (InputMethodManager)ctx.getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow( view.getWindowToken(), 0 );
	}

	/**
	 * 过滤非法的字符
	 * @param key
	 * @return
	 */
	private String vali( String key ) {
		if( null == key ) return "";
		String s = key.trim();
		String c = s.substring(0,1);
		if( c.equals( "#") || c.equals( "%" ) ) return s.substring( 1 );
		return s;
	}



	@Override
	public void onFinished( PageInfo page ) {
		if( null == page ) {
			mTextViewResult.setText( String.format( ctx.getResources().getString( R.string.soft_mgr_search_result), mKeyword, "" + 0 ) );
		} else {
			if ( !bSetResultHit ) {
				bSetResultHit = true;
				mTextViewResult.setText( String.format( ctx.getResources().getString( R.string.soft_mgr_search_result), mKeyword, page.totalRecordNums ) );
			}
		}
		resultLayout.setVisibility( View.VISIBLE );
	}


	@Override
	public void onStarting() {
		// TODO Auto-generated method stub
		
	}
	
	/**
	 * 返回true表示移除了View、消化处理了back键
	 * @param resultsView
	 * @return
	 */
	public boolean removeResultView(){
		
		if ( container!=null && searchResultView!=null && searchResultView.isShown() ){	
			searchResultView.clearCache();
			container.removeView(searchResultView);
			searchResultView = null;
			resultLayout.setVisibility( View.GONE );
			
			return true;
		}
		return false;
	}
	
	/**
	 * 1、返回back会调用次函数
	 * 2、再次点击选中的Tab时也会调用次函数,表示刷新View
	 */
	@Override
	public boolean flushView() {
		
		return removeResultView();
	}

	View.OnClickListener catagorySearchListener = new View.OnClickListener(){
		public void onClick(View v) {
			
			if (v instanceof TextView) {
				
				SoftInfo catagory = (SoftInfo)v.getTag();
			}
		}
	};
	
	View.OnClickListener hotSearchListener = new View.OnClickListener(){
		public void onClick(View v) {
			
			if (v instanceof TextView) {
				
				searchNameType = false;
				
				String hotSearchKey = ((TextView) v).getText().toString();
				//mEditKeyword.setText(hotSearchKey);
				searchByKeyWord( hotSearchKey );
			}
		}
	};

	View.OnClickListener hotSoftListener = new View.OnClickListener(){
		public void onClick(View v) {
			SoftInfo softInfo = (SoftInfo)v.getTag();
			Intent intent=new Intent(ctx,SoftMgrDetailActivity.class);
			int iSoftID = Integer.valueOf(softInfo.getSid());
			intent.putExtra("softID",iSoftID);
			ctx.startActivity(intent);
		}
	};
		
	public static void initCacheData(){
		if (listSoftInfo==null || listHotKey==null){ 
			// 加载分类及热门软件
			new Thread(new Runnable() {
				@Override
				public void run() {
					if ( listSoftInfo==null )
						listSoftInfo = CoachSiteSoftMgrApiAccessor.getSoftMgRecommendList();
					
					if ( listHotKey==null )
						listHotKey = CoachSiteSoftMgrApiAccessor.getSoftMgrKeywordList();
				}
			}).start();
		}
	}
}
